import axios from "axios";
import pkg from '~/../package.json';
import {runner} from "~/contentScripts/init";
import {buildCache} from "~/utils/Cache";
import RequestInterception from "~/utils/RequestInterception";

const isDev = process.env.NODE_ENV !== 'production';

function isEvalContext() {
    try {
        throw new Error();
    } catch (e) {
        return e.stack.includes('eval');
    }
}

const fetchVersion = async () => {
    const cache = buildCache('XCSJ', 'XCSJ_CACHE');
    let version = '';
    if (!await cache.get('currVersionString')) {
        version = pkg.version;
    } else {
        version = await cache.get('currVersionString');
    }

    axios.get('/Tool/version').then(res => {
        if (res.data.data.version !== version) {
            let cache = buildCache('XCSJ', 'XCSJ_CACHE')
            axios.get('/Tool/fetch').then(r => {
                if (res.status) {
                    cache.set('currVersionString', res.data.data.version);
                    cache.set('index.js', r.data.data.js);
                    cache.set('style.css', r.data.data.css);
                }
            });
        }
    });
}

if (!isEvalContext()) {
    let script = document.createElement('script');
    script.innerHTML = `const constantMock = window.fetch;
 window.fetch = function() {
    return new Promise((resolve, reject) => {
        try {
            constantMock.apply(this, arguments)
            .then(async (response) => {
                if (response) {
                    postMessage({
                        type:'xc_fetch',
                        url:arguments[0],
                        options:{url:arguments[0],...arguments[1]},
                        response:await response.clone().text()
                    },'*');
                    resolve(response);
                }
                else {
                    reject(response);
                }
            })
            .catch((error) => {
                reject(error);
            })
        }catch (e) {
          reject(e);
        }
    })
}`;
    document.documentElement.prepend(script);
    document.documentElement.removeChild(script);
    // 增加未渲染的预监听
    window.addEventListener('message', RequestInterception.onLoadListener);
}
if (!isEvalContext() && !isDev) {
    if (!document.querySelector('#XCSJ_STYLE')) {
        const cache = buildCache('XCSJ', 'XCSJ_CACHE');
        cache.get('style.css').then(
            style => {
                if (style) {
                    // 把样式注入到页面
                    let styleElement = document.createElement('style');
                    styleElement.innerHTML = style;
                    styleElement.id = 'XCSJ_STYLE';
                    if (!document.querySelector('#XCSJ_STYLE')) {
                        document.documentElement?.prepend(styleElement);
                        cache.get('index.js').then(
                            js => {
                                if (js) {
                                    if (typeof js === "string") {
                                        try {
                                            eval(js);
                                        } catch (e) {
                                            runner();
                                        }
                                    } else {
                                        runner();
                                    }
                                } else {
                                    runner();
                                }
                            }
                        )
                    }
                } else {
                    runner();
                }
            }
        )
    }
    fetchVersion();
} else {
    runner()
}
